import React, { useEffect, useState, useRef } from "react";
import { Form, Input, Button, Select, Checkbox, Row, Col, message, AutoComplete, Cascader, Space } from "antd";
import { getMessageCode, checkMessageCode, submitWithWeCom, getMore, getEnumData } from "@/api";
import SuccessModal from "./Home/SuccessModal";
import { debounce, getCsrf, getPageSourceInfo } from "../../../shared/util";

function StoreForm(props: any) {
	const { extText, setShowSuccessModal, setQrUrl } = props;
	const { origin, joinSource } = getPageSourceInfo();
	const [formWrapper] = Form.useForm();
	const [form, setForm] = useState<any>({});
	const [seconds, setSeconds] = useState(60);
	const secondsRef = useRef(seconds);
	const [isSend, setIsSend] = useState(false);
	const [moreList, setMoreList] = useState<any>([]);
	const [companyList, setCompanyList] = useState<any>([]);
	const [regionList, setRegionList] = useState<any>([]);
	const [isAbleStore, setIsAbleStore] = useState(false);
	const [companyInfo, setCompanyInfo] = useState<any>({});
	// const [showSuccessModal, setShowSuccessModal] = useState(false);
	const [showCompanyDetail, setShowCompanyDetail] = useState(false);
	useEffect(() => {
		getMore({
			origin,
		}).then((res: any) => {
			if (res?.success) {
				const escape2Html = (str: string) => {
					var arrEntities: any = { lt: "<", gt: ">", nbsp: " ", amp: "&", quot: '"' };
					return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
						return arrEntities[t];
					});
				};
				const values = JSON.parse(escape2Html(res?.values?.configurationStr));
				setMoreList(values[0].value);
			}
		});
		getEnumData({
			namespace: "getChinaRegionList",
			widgetId: "getChinaRegionList",
			methodName: "execute",
			reginId: 1,
		}).then((res: any) => {
			console.log(res);
			const values = res.content.result.values?.map((item: any) => {
				return {
					...item,
					label: item.divisionName,
					value: item.divisionId,
					isLeaf: false,
				};
			});
			setRegionList(values);
		});
	}, []);
	useEffect(() => {
		console.log("form", form)
		setIsAbleStore(form.linkManName && form.phone && form.messageCode && form.checked && (companyInfo.ENT_NAME || form.companyName) && form.regionInfo?.district && (companyInfo.address || form.address));
		if (!form.companyName) {
			setShowCompanyDetail(false);
			setCompanyInfo({});
		}
	}, [form]);

	useEffect(() => {
		// 及时更新 count 值
		secondsRef.current = seconds;
	});
	useEffect(() => {
		let _interval: any;
		if (isSend) {
			_interval = setInterval(() => {
				if (secondsRef.current < 1) {
					setIsSend(false);
					setSeconds(60);
					clearInterval(_interval);
				} else {
					setSeconds((n) => n - 1);
				}
			}, 1000);
		}
		return () => {
			_interval && clearInterval(_interval);
		};
	}, [isSend]);

	const onFinish = async () => {
		// setQrUrl(require("@/assets/imgs/person.png"));
		// props.onHide && props.onHide();
		// setShowSuccessModal(true);
		// props.setShowFooter && props.setShowFooter(false);
		// formWrapper.resetFields();
		// setForm({})
		// return;
		const res: any = await checkMessageCode({
			phone: form.phone,
			messageCode: form.messageCode,
		});
		if (res.success) {
			const params = {
				address: companyInfo.address || form.address,
				companyName: companyInfo.ENT_NAME || form.companyName,
				linkManName: form.linkManName,
				countryPhoneCode: "86",
				// "local": companyInfo.bizRegNo,
				mobilePhone: form.phone,
				socialCreditCode: companyInfo.creditCode,
				origin: origin,
				willingnessKeys: form.willingnessKeys,
				pageUrl: location.href.includes("localhost:") ? "https://supplier.alibaba.com/" : location.href,
				joinSource: joinSource,
				...form.regionInfo,
			};

			submitWithWeCom({
				phone: form.phone,
				messageCode: form.messageCode,
				data: JSON.stringify(params),
				pcsrf: getCsrf(),
			}).then((res: any) => {
				if (res.success) {
					setQrUrl(res.values.saleWeComQrUrl);
					props.onHide && props.onHide();
					setShowSuccessModal(true);
					props.setShowFooter && props.setShowFooter(false);
					formWrapper.resetFields();
					setForm({})
					if ((window as any) && (window as any).goldlog) {
						(window as any).goldlog.record(
							"/sc.supplier.newsign",
							"CLK",
							`btn=submit_success&status=success&origin=${origin}`,
							"POST"
						);
					}
				} else {
					message.error(res.errorMsg);
					if ((window as any) && (window as any).goldlog) {
						(window as any).goldlog.record(
							"/sc.supplier.newsign",
							"CLK",
							`btn=submit_fail&status=validate_fail&origin=${origin}`,
							"POST"
						);
					}
				}
			});
		} else {
			message.error("验证码错误");
			if ((window as any) && (window as any).goldlog) {
				(window as any).goldlog.record(
					"/sc.supplier.newsign",
					"CLK",
					`btn=submit_fail&status=phone_code_valid_fail&origin=${origin}`,
					"POST"
				);
			}
		}
	};
	const onFinishFailed = () => { };
	const handleGetCode = () => {
		if (isSend) return;
		if (!/^1[3-9]\d{9}$/.test(form.phone)) {
			message.error("请输入正确的手机号");
			return;
		}
		getMessageCode({
			phone: form.phone,
		}).then((res: any) => {
			if (res.success) {
				message.success("验证码发送成功");
				setIsSend(true);
			} else {
				message.error(res.errorMsg);
			}
		});
	};
	const handleForm = (value: any, type: string) => {
		const newForm = {
			...form,
			[type]: value,
		};
		setForm(newForm);
	};
	const handleSearchCompany = (value: any) => {
		if (!value) return;
		getEnumData({
			keyword: value,
			namespace: "searchEnterpriseName",
			widgetId: "searchEnterpriseName",
			methodName: "execute",
			limit: 10,
		}).then((res: any) => {
			const values = res.content.result.values?.map((item: any) => {
				return {
					label: item,
					value: item,
				};
			});
			setCompanyList(values);
			setShowCompanyDetail(true);
			if (res.content.result.total === 0) {
				setForm({
					...form,
					companyName: value
				})
				setCompanyInfo({})
				formWrapper.setFieldValue("address", "");
				formWrapper.setFieldValue("companyRegion", []);
			}
		});
	};
	const handleSelectCompany = (e: any) => {
		getEnumData({
			namespace: "searchEnterpriseInfo",
			widgetId: "searchEnterpriseInfo",
			methodName: "execute",
			name: e,
		}).then((res: any) => {
			const values = res.content.result.values;
			if (!values) return;
			console.log("values", values);
			setCompanyInfo(values);
			formWrapper.setFieldValue("address", values.address);
			const companyRegion = values.addressVo ? [
				values.addressVo.provinceName,
				values.addressVo.cityName,
				values.addressVo.regionName,
				values.addressVo.streetName,
			] : []
			formWrapper.setFieldValue("companyRegion", companyRegion);
			const avo = values.addressVo;
			const regionInfo = {
				city: avo.cityName,
				cityCode: avo.cityCode,
				district: avo.regionName,
				districtCode: avo.regionCode,
				province: avo.provinceName,
				provinceCode: avo.provinceCode,
				street: avo.streetName,
				streetCode: avo.streetCode,
				local: avo.streetCode,
			};
			setForm({
				...form,
				regionInfo,
				companyName: values.ENT_NAME,
				address: values.address
			})
		});
	};
	const loadRegionData = (e: any) => {
		const firstIndex = regionList.findIndex((item: any) => item.value === e[0].value);
		const secondIndex =
			e.length > 1 ? regionList[firstIndex].children.findIndex((item: any) => item.value === e[1].value) : null;
		const thirdIndex =
			e.length === 3
				? regionList[firstIndex].children[secondIndex].children.findIndex(
					(item: any) => item.value === e[e.length - 1].value
				)
				: null;
		let regionId;
		switch (e.length) {
			case 1:
				regionId = regionList[firstIndex].divisionId;
				break;
			case 2:
				regionId = regionList[firstIndex].children[secondIndex].divisionId;
				break;
			case 3:
				regionId = regionList[firstIndex].children[secondIndex].children[thirdIndex].divisionId;
				break;
			default:
				break;
		}
		getEnumData({
			namespace: "getChinaRegionList",
			widgetId: "getChinaRegionList",
			methodName: "execute",
			reginId: regionId,
		}).then((res: any) => {
			const values = res.content.result.values?.map((item: any) => {
				return {
					...item,
					label: item.divisionName,
					value: item.divisionId,
					isLeaf: item.divisionName === "其它区" || e.length === 3,
				};
			});
			if (e.length === 1) {
				regionList[firstIndex].children = values;
			} else if (e.length === 2) {
				regionList[firstIndex].children[secondIndex].children = values;
			} else if (e.length === 3) {
				regionList[firstIndex].children[secondIndex].children[thirdIndex].children = values;
			}
			setRegionList([...regionList]);
		});
	};
	const handleChangeAddress = (e: any) => {
		if (e.length < 3) return;
		const firstIndex: any = regionList.findIndex((item: any) => item.value == e[0]);
		const secondIndex = regionList[firstIndex].children.findIndex((item: any) => item.value == e[1]);
		const thirdIndex = regionList[firstIndex].children[secondIndex].children.findIndex(
			(item: any) => item.value == e[2]
		);
		const fourIndex =
			e.length === 4
				? regionList[firstIndex].children[secondIndex].children[thirdIndex].children.findIndex(
					(item: any) => item.value == e[3]
				)
				: 0;
		const regionInfo = {
			city: regionList[firstIndex].children[secondIndex].label,
			cityCode: regionList[firstIndex].children[secondIndex].value,
			district: regionList[firstIndex].children[secondIndex].children[thirdIndex].label,
			districtCode: regionList[firstIndex].children[secondIndex].children[thirdIndex].value,
			province: regionList[firstIndex].label,
			provinceCode: regionList[firstIndex].value,
			street:
				e.length === 4
					? regionList[firstIndex].children[secondIndex].children[thirdIndex].children[fourIndex].label
					: "",
			streetCode:
				e.length === 4
					? regionList[firstIndex].children[secondIndex].children[thirdIndex].children[fourIndex].value
					: "",
			local:
				e.length === 4
					? regionList[firstIndex].children[secondIndex].children[thirdIndex].children[fourIndex].value
					: "",
		};
		setForm({
			...form,
			regionInfo,
		});
	};
	return (
		<div className={`store-form ${showCompanyDetail ? "has-company-form" : ""}`}>
			<Form
				name={props.formName}
				form={formWrapper}
				labelAlign='left'
				labelWrap={true}
				labelCol={{
					span: 24,
				}}
				style={{
					maxWidth: 460,
				}}
				initialValues={{
					remember: true,
				}}
				onFinish={onFinish}
				onFinishFailed={onFinishFailed}
				autoComplete='off'>
				<Form.Item
					label='公司名称'
					name='companyName'
					rules={[
						{
							required: true,
							message: "请输入",
						},
					]}>
					<AutoComplete
						onSearch={debounce(handleSearchCompany, 1200)}
						onSelect={(e: any) => handleSelectCompany(e)}
						onChange={(e) => handleForm(e, "companyName")}
						options={companyList}
					/>
				</Form.Item>
				<Form.Item
					label='姓名'
					name='linkManName'
					rules={[
						{
							required: true,
							message: "请输入",
						},
					]}>
					<Input onChange={(e) => handleForm(e.target.value, "linkManName")} />
				</Form.Item>
				<Row>
					<Col span={15}>
						<Form.Item
							name='phone'
							label='手机号码'
							rules={[
								{
									required: true,
									message: "请输入",
								},
								{
									validator: (_, value) => {
										return !/^1[3-9]\d{9}$/.test(value)
											? Promise.reject("请输入正确的手机号")
											: Promise.resolve();
									},
								},
							]}>
							<div className='phone-wrapper'>
								<Input
									addonBefore='86'
									onChange={(e: any) => handleForm(e.target.value, "phone")}
									placeholder='请输入'
								/>
								<span
									className={`btn-get-code ${/^1[3-9]\d{9}$/.test(form.phone) && !isSend ? "active-get" : ""
										}`}
									onClick={handleGetCode}>
									{isSend ? seconds + "s重新获取" : "获取验证码"}
								</span>
							</div>
						</Form.Item>
					</Col>
					<Col span={1}></Col>
					<Col span={8}>
						<Form.Item
							name='messageCode'
							label='验证码'
							rules={[
								{
									required: true,
									message: "请输入",
								},
							]}>
							<Input
								placeholder='请输入'
								onChange={(e: any) => handleForm(e.target.value, "messageCode")}
							/>
						</Form.Item>
					</Col>
				</Row>
				{showCompanyDetail ? (
					<>
						<Form.Item
							label='公司地址'
							name='companyRegion'
							rules={[
								{
									required: true,
									message: "请输入",
								},
							]}>
							<Cascader
								options={regionList}
								allowClear={false}
								changeOnSelect
								loadData={loadRegionData}
								onChange={handleChangeAddress}
							/>
						</Form.Item>
						<Form.Item
							label='详细地址'
							name='address'
							rules={[
								{
									required: true,
									message: "请输入",
								},
							]}>
							<Input onChange={(e) => handleForm(e.target.value, "address")} />
						</Form.Item>
					</>
				) : null}
				<Form.Item name='more' label={extText || "了解更多"}>
					<Select
						mode='multiple'
						value={form.more}
						onChange={(e: any) => handleForm(e, "willingnessKeys")}
						options={moreList}
						maxTagCount='responsive'
						optionRender={(option) => (
							<Space>
								<Checkbox
									checked={form.willingnessKeys?.includes(option.data.value)}
									className='disabled-click'></Checkbox>
								<span>{option.data.label}</span>
							</Space>
						)}
					/>
				</Form.Item>
				<Form.Item name='remember'>
					<Checkbox
						onChange={(e) => {
							handleForm(e.target.checked, "checked");
						}}>
						为向您提供个性化的营销服务，您知悉并同意Alibaba.com会根据其
						<a
							href='https://rule.alibaba.com/rule/detail/11000427.htm?spm=a27am.13680033.0.0.7ee9aeb6bmdIxG'
							target='_blank'>
							《隐私权政策》
						</a>
						收集以及使用您的上述信息。
					</Checkbox>
				</Form.Item>
				<Form.Item className='submit-wrapper'>
					<Button className='btn-consult' disabled={!isAbleStore} type='primary' htmlType='submit'>
						开店咨询
					</Button>
				</Form.Item>
			</Form>
			{/* {
				showSuccessModal &&
				<SuccessModal
					showSuccessModal={showSuccessModal}
					setShowSuccessModal={setShowSuccessModal}
					qrUrl={qrUrl}
					setQrUrl={setQrUrl}
					onHideForm={props.onHide}
				></SuccessModal>
			} */}

		</div>
	);
}

export default StoreForm;
